package com.yonyou.brigade.ybz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yonyou.brigade.order_center.model.*;
import com.yonyou.brigade.order_center.service.*;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.brigade.ybz.model.BriOrderNote;
import com.yonyou.brigade.ybz.dao.BriOrderNoteMapper;
import com.yonyou.brigade.ybz.service.IBriOrderNoteService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.brigade.ybz.service.IConvertTemplateMappingService;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import org.apache.poi.ss.formula.functions.T;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author duhqh@yonyou.com
 * @since 2018-10-20
 */
@Service
public class BriOrderNoteServiceImpl extends ServiceImpl<BriOrderNoteMapper, BriOrderNote> implements IBriOrderNoteService {

    private static Logger logger = LoggerFactory.getLogger(BriOrderNoteServiceImpl.class);

    private static String dateFormat = "yyyy-MM-dd";

    @Autowired
    private BriOrderNoteMapper briOrderNoteMapper;

    @Value("${ybz.open.note}")
    private String NOTE_URL;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.brigade.flight.tradetype}")
    private String flightTradetype;

    @Value("${cnv.brigade.hotel.tradetype}")
    private String hotelTradetype;

    @Value("${cnv.brigade.train.tradetype}")
    private String trainTradetype;

    @Value("${cnv.brigade.car.tradetype}")
    private String carTradetype;

    @Autowired
    private IBriOrderService briOrderService;

    @Autowired
    @Qualifier("briFlightOrderServiceImpl")
    private IBriFlightOrderService briFlightOrderService;

    @Autowired
    private IBriFlightInfoService briFlightInfoService;

    @Autowired
    @Qualifier("briHotelOrderServiceImpl")
    private IBriHotelOrderService briHotelOrderService;

    @Autowired
    @Qualifier("briTrainOrderServiceImpl")
    private IBriTrainOrderService briTrainOrderService;

    @Autowired
    @Qualifier("briCarOrderServiceImpl")
    private IBriCarOrderService briCarOrderService;

    @Autowired
    private IConvertService convertService;

    @Autowired
    private IConvertTemplateMappingService convertTemplateMappingService;

    @Override
    public void updateOrderBxState(List<String> notePks,int state)
    {
        if(notePks!=null&&notePks.size()>0)
        {
            List<BriOrderNote> briOrderNotes=briOrderNoteMapper.getOrderNotesByNotePks(notePks);
            if(briOrderNotes!=null&&briOrderNotes.size()>0)
            {
                List<Integer> flightInfos=new ArrayList<>();
                List<Integer> hotelInfos=new ArrayList<>();
                List<Integer> trainInfos=new ArrayList<>();
                for(int i=0;i<briOrderNotes.size();i++)
                {
                    BriOrderNote briOrderNote=briOrderNotes.get(i);
                    if(briOrderNote.getOrderType().equals("flight_order"))
                    {
                        flightInfos.add(briOrderNote.getId());
                    }
                    else if(briOrderNote.getOrderType().equals("hotel_order"))
                    {
                        hotelInfos.add(briOrderNote.getId());
                    }
                    else if(briOrderNote.getOrderType().equals("brigade_trainDo_tradetype"))
                    {
                        trainInfos.add(briOrderNote.getId());
                    }
                }
                if(flightInfos!=null&&flightInfos.size()>0)
                {
                    briFlightOrderService.updateIsBxStateByOrderIds(flightInfos,state);
                }
                if(hotelInfos!=null&&hotelInfos.size()>0)
                {
                    briHotelOrderService.updateIsBxStateByOrderIds(hotelInfos,state);
                }
                if(trainInfos!=null&&trainInfos.size()>0)
                {
                    briTrainOrderService.updateIsBxStateByOrderIds(trainInfos,state);
                }
            }
        }

    }

    public List<BriOrderNote> getBriOrderNotesByRelateYBZIds(Map<String,List<String>> map)
    {
        List<BriOrderNote> briOrderNotes=new ArrayList<>();

        List<String> flights=map.get("flight");
        List<String> hotels=map.get("hotel");
        List<String> trains=map.get("train");
        List<String> cars=map.get("car");
        if(flights!=null&&flights.size()>0)
        {
            List<BriFlightOrder> briFlightOrderList=briFlightOrderService.getOrdersByRelateYBZId(flights);
            if(briFlightOrderList!=null&&briFlightOrderList.size()>0)
            {
                List<String> ids=new ArrayList<>();
                for(int i=0;i<briFlightOrderList.size();i++)
                {
                    ids.add(String.valueOf( briFlightOrderList.get(i).getId()));
                }
                Map mapParams=new HashMap();
                mapParams.put("list",ids);
                mapParams.put("orderType","flight_order");
                List<BriOrderNote> temp=briOrderNoteMapper.getNoteByApplyNo(mapParams);
                if(temp!=null)
                {
                    briOrderNotes.addAll(temp);
                }
            }
        }
        if(hotels!=null&&hotels.size()>0)
        {
            List<BriHotelOrder> briHotelOrderList=briHotelOrderService.getOrdersByRelateYBZId(hotels);
            if(briHotelOrderList!=null&&briHotelOrderList.size()>0)
            {
                List<String> ids=new ArrayList<>();
                for(int i=0;i<briHotelOrderList.size();i++)
                {
                    ids.add(String.valueOf( briHotelOrderList.get(i).getId()));
                }
                Map mapParams=new HashMap();
                mapParams.put("list",ids);
                mapParams.put("orderType","hotel_order");
                List<BriOrderNote> temp=briOrderNoteMapper.getNoteByApplyNo(mapParams);
                if(temp!=null)
                {
                    briOrderNotes.addAll(temp);
                }
            }
        }
        if(trains!=null&&trains.size()>0)
        {
            List<BriTrainOrder> briTrainOrderList=briTrainOrderService.getOrdersByRelateYBZId(trains);
            if(briTrainOrderList!=null&&briTrainOrderList.size()>0)
            {
                List<String> ids=new ArrayList<>();
                for(int i=0;i<briTrainOrderList.size();i++)
                {
                    ids.add(String.valueOf( briTrainOrderList.get(i).getId()));
                }
                Map mapParams=new HashMap();
                mapParams.put("list",ids);
                mapParams.put("orderType","brigade_trainDo_tradetype");
                List<BriOrderNote> temp=briOrderNoteMapper.getNoteByApplyNo(mapParams);
                if(temp!=null)
                {
                    briOrderNotes.addAll(temp);
                }
            }
        }
        if(cars!=null&&cars.size()>0)
        {
            List<BriCarOrder> briCarOrderList=briCarOrderService.getOrdersByRelateYBZId(cars);
            if(briCarOrderList!=null&&briCarOrderList.size()>0)
            {
                List<String> ids=new ArrayList<>();
                for(int i=0;i<briCarOrderList.size();i++)
                {
                    ids.add(String.valueOf( briCarOrderList.get(i).getId()));
                }
                Map mapParams=new HashMap();
                mapParams.put("list",ids);
                mapParams.put("orderType","car_order");
                List<BriOrderNote> temp=briOrderNoteMapper.getNoteByApplyNo(mapParams);
                if(temp!=null)
                {
                    briOrderNotes.addAll(temp);
                }
            }
        }
        return briOrderNotes;
    }

    public Map<String,List<String>> getNotePksByYBZIds(Map<String,List<String>> map) {
        Map<String, List<String>> result = new HashMap<>();
        List<BriOrderNote> briOrderNotes = getBriOrderNotesByRelateYBZIds(map);
        if (briOrderNotes != null && briOrderNotes.size() > 0)
        {
            for(int i=0;i<briOrderNotes.size();i++)
            {
                if(result.containsKey(briOrderNotes.get(i).getNoteType()))
                {
                    result.get(briOrderNotes.get(i).getNoteType()).add(briOrderNotes.get(i).getNotePk());
                }
                else
                {
                    List<String> list=new ArrayList<>();
                    list.add(briOrderNotes.get(i).getNotePk());
                    result.put(briOrderNotes.get(i).getNoteType(),list);
                }
            }
        }
        return result;
    }

    @Override
    public void updateNoteState(Map<String,Map<String,Integer>> noteStates)
    {
        if(noteStates!=null&&noteStates.size()>0)
        {
            for(Map.Entry<String,Map<String,Integer>> entry:noteStates.entrySet())
            {
                String voucherPk=entry.getKey();
                Map<String,Integer> notes=entry.getValue();
                if(notes!=null&&notes.size()>0) {
                    for (Map.Entry<String, Integer> entry1 : notes.entrySet()) {
                        String notePk = entry1.getKey();
                        int state = entry1.getValue();
                        Map params = new HashMap();
                        params.put("notePk", notePk);
                        params.put("noteState", state);
                        params.put("voucherPk", voucherPk);
                        briOrderNoteMapper.updateNoteState(params);
                    }
                }
            }
        }

    }

    @Override
    public JSONObject getNoteInfosByApplyIds(String tenant, Map params)
    {
        Map<String,List<String>> noteIdMap=getNotePksByYBZIds(params);
        List<String> noteIdList=new ArrayList<>();
        if(noteIdMap!=null&&noteIdMap.size()>0)
        {
            for(Map.Entry<String,List<String>> entry:noteIdMap.entrySet())
            {
                List<String> noteIds=entry.getValue();
                if(noteIds!=null&&noteIds.size()>0)
                {
                    noteIdList.addAll(noteIds);
                }
            }
        }
        Map ybzParams=new HashMap();
        ybzParams.put("pks", noteIdList);
        String url = ybzBaseUrl + NOTE_URL+"?tenantId="+tenant;
        logger.info("通过记事pks调用ybz查询账本列表的参数：租户为" + tenant + ",ybzParams：" + JSON.toJSONString(ybzParams));
        String result= HttpClientUtil.doPostJson(url,JSONObject.toJSONString(ybzParams));
        JSONObject jsonObject=JSONObject.parseObject(result);
        logger.info("通过记事pks调用ybz查询账本列表的返回：" + result);
        addApplyIdAndflightInfos(jsonObject);
        return jsonObject;
    }

    /**
     * 订单转记事（可传记事类型）
     * @param params
     * @return
     */
    @Override
    public JSONArray convert(JSONArray params) {
        JSONArray resultArray = new JSONArray();
        Map<String, String> notedMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(params)) {
            for (Object param : params) {
                JSONObject paramJSON = JSONObject.parseObject(JSON.toJSONString(param));
                JSONArray orders = paramJSON.getJSONArray("orders");
                if (!CollectionUtils.isEmpty(orders)) {
                    String noteCode = paramJSON.getString("noteCode");
                    for (Object order : orders) {
                        JSONObject orderJson = JSONObject.parseObject(JSON.toJSONString(order));
                        String orderNo = orderJson.getString("orderNo");
                        if (notedMap.containsKey(orderNo)){
                            continue;
                        }else {
                            notedMap.put(orderNo, "");
                        }
                        String orderClassification = orderJson.getString("orderClassification");
                        if (StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(orderClassification)) {
                            throw new BusinessException("请检查订单相关参数");
                        }
                        JSONArray relationOrderArr = new JSONArray();
                        JSONObject orderJSON = new JSONObject();
                        String tradeType = new String();
                        // 根据订单编号和订单类别查询符合生成记事的订单
                        if (CnvFlightOrderDO.FLIGHT.equals(orderClassification)) {
                            CnvFlightOrderDO cnvFlightOrderDO = briFlightOrderService.getBriFlightOrderByOrderNo(orderNo);
                            orderJSON = JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvFlightOrderDO, dateFormat, SerializerFeature.WriteDateUseDateFormat));
                            tradeType = flightTradetype;
                            //与该订单关联的原单或退改单
                            List<CnvFlightOrderDO> relationOrderList = briFlightOrderService.getRelationOrders(orderNo, cnvFlightOrderDO.getParentOrderNo(), cnvFlightOrderDO.getFromType(), cnvFlightOrderDO.getTenant());
                            String jsonString = JSON.toJSONStringWithDateFormat(relationOrderList, dateFormat, SerializerFeature.WriteDateUseDateFormat);
                            relationOrderArr = JSONArray.parseArray(jsonString);

                        } else if (CnvHotelOrderDO.HOTEL.equals(orderClassification)) {
                            CnvHotelOrderDO cnvHotelOrderDO = briHotelOrderService.getBriHotelOrderByOrderNo(orderNo);
                            orderJSON = JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvHotelOrderDO, dateFormat, SerializerFeature.WriteDateUseDateFormat));
                            tradeType = hotelTradetype;

                            //与该订单关联的原单或退改单
                            List<CnvHotelOrderDO> relationOrderList = briHotelOrderService.getRelationOrders(orderNo, cnvHotelOrderDO.getParentOrderNo(), cnvHotelOrderDO.getFromType(), cnvHotelOrderDO.getTenant());
                            String jsonString = JSON.toJSONStringWithDateFormat(relationOrderList, dateFormat, SerializerFeature.WriteDateUseDateFormat);
                            relationOrderArr = JSONArray.parseArray(jsonString);

                        } else if (CnvTrainOrderDO.TRAIN.equals(orderClassification)) {
                            CnvTrainOrderDO cnvTrainOrderDO = briTrainOrderService.getBriTrainOrderByOrderNo(orderNo);
                            orderJSON = JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvTrainOrderDO, dateFormat, SerializerFeature.WriteDateUseDateFormat));
                            tradeType =trainTradetype;

                            //与该订单关联的原单或退改单
                            List<CnvTrainOrderDO> relationOrderList = briTrainOrderService.getRelationOrders(orderNo, cnvTrainOrderDO.getParentOrderNo(), cnvTrainOrderDO.getFromType(), cnvTrainOrderDO.getTenant());
                            String jsonString = JSON.toJSONStringWithDateFormat(relationOrderList, dateFormat, SerializerFeature.WriteDateUseDateFormat);
                            relationOrderArr = JSONArray.parseArray(jsonString);
                        } else if (CnvCarOrderDO.CAR.equals(orderClassification)) {
                            CnvCarOrderDO cnvCarOrderDO = briCarOrderService.getBriCarOrderByOrderNo(orderNo);
                            orderJSON = JSON.parseObject(JSON.toJSONStringWithDateFormat(cnvCarOrderDO, DateUtils.DD_DATETIME_FORMAT, SerializerFeature.WriteDateUseDateFormat));
                            tradeType = carTradetype;
                        }
                        orderJSON = mergeOrders(orderJSON, relationOrderArr, orderClassification,notedMap);
                        JSONObject resultJSON = convertService.convert(tradeType, systemCode, orderJSON.getString("userId"), orderJSON.getString("tenant"), null, orderJSON);
                        detailCvtResult(resultJSON, noteCode, orderJSON.getString("orderNo"), orderClassification, resultArray, notedMap);
                        //处理和该订单相关的原单或退改单
//                        logger.info("开始转换关联订单");
//                        for (int i = 0; i < relationOrderArr.size(); i++) {
//                            JSONObject relationOrder = relationOrderArr.getJSONObject(i);
//                            JSONObject relationRs = convertService.convert(tradeType, systemCode, relationOrder.getString("userId"), orderJSON.getString("tenant"), null, relationOrder);
//                            detailCvtResult(relationRs, noteCode, relationOrder.getString("orderNo"), orderClassification, resultArray, notedMap);
//                        }
//                        logger.info("转换关联订单结束");
                    }
                }
            }
        } else {
            throw new BusinessException("请检查参数");
        }
        return resultArray;
    }

    /**
     * 将订单与订单的关联订单合并，取最后一条订单记录的开始时间和结束时间，
     * 取所有关联订单最终支付金额（payment_price）的合计作为金额，
     * 去最后一条订单记录的订单号作为合并订单的订单号，并将原单号保存在另外一个字段中
     * 取最后一个订单记录的单据类型（N/G/T），作为本合并订单的单据类型
     * @param orderJSON
     * @param relationOrderArr
     * @param orderClassification
     * @return
     */
    private JSONObject mergeOrders(JSONObject orderJSON, JSONArray relationOrderArr, String orderClassification, Map<String, String> noteMap) {
        JSONObject resultOrder = orderJSON;
        BigDecimal paymentPrice = orderJSON.getBigDecimal("paymentPrice");
        JSONObject refundOrder = null;
        JSONObject changeOrder = null;
        //单人票面价
        BigDecimal farePrice = orderJSON.getBigDecimal("farePrice");
        //基建/税费
        BigDecimal constructionPrice = orderJSON.getBigDecimal("constructionPrice");
        //燃油
        BigDecimal oilfee = orderJSON.getBigDecimal("oilfee");
        //改签费
        BigDecimal changeFee = orderJSON.getBigDecimal("changeFee");
        //退票费
        BigDecimal tpPrice = orderJSON.getBigDecimal("tpPrice");
        //订单总服务费
        BigDecimal sumCounterFee = orderJSON.getBigDecimal("sumCounterFee");
        //送票费
        BigDecimal sendTicketFee = orderJSON.getBigDecimal("sendTicketFee");
        //保险费
        BigDecimal sumInsMoney = orderJSON.getBigDecimal("sumInsMoney");
        //火车票票面价
        BigDecimal tktPrice = orderJSON.getBigDecimal("tktPrice");
        //改签总变更费
        BigDecimal carrierSumFee = orderJSON.getBigDecimal("carrierSumFee");
        for (int i = 0; i < relationOrderArr.size(); i++) {
            JSONObject relationOrder = relationOrderArr.getJSONObject(i);
            noteMap.put(relationOrder.getString("orderNo"),"");
            String orderType = relationOrder.getString("orderType");
            String statusType = relationOrder.getString("statusType");
            if (paymentPrice != null && relationOrder.getBigDecimal("paymentPrice") != null){
                paymentPrice = paymentPrice.add(relationOrder.getBigDecimal("paymentPrice"));
            }
            if (farePrice != null && relationOrder.getBigDecimal("farePrice") != null){
                farePrice = farePrice.add(relationOrder.getBigDecimal("farePrice"));
            }
            if (constructionPrice != null && relationOrder.getBigDecimal("constructionPrice") != null){
                constructionPrice = constructionPrice.add(relationOrder.getBigDecimal("constructionPrice"));
            }
            if (oilfee != null && relationOrder.getBigDecimal("oilfee") != null){
                oilfee = oilfee.add(relationOrder.getBigDecimal("oilfee"));
            }
            if (changeFee != null && relationOrder.getBigDecimal("changeFee") != null){
                changeFee = changeFee.add(relationOrder.getBigDecimal("changeFee"));
            }
            if (tpPrice != null && relationOrder.getBigDecimal("tpPrice") != null){
                tpPrice = tpPrice.add(relationOrder.getBigDecimal("tpPrice"));
            }
            if (sumCounterFee != null && relationOrder.getBigDecimal("sumCounterFee") != null){
                sumCounterFee = sumCounterFee.add(relationOrder.getBigDecimal("sumCounterFee"));
            }
            if (sendTicketFee != null && relationOrder.getBigDecimal("sendTicketFee") != null){
                sendTicketFee = sendTicketFee.add(relationOrder.getBigDecimal("sendTicketFee"));
            }
            if (sumInsMoney != null && relationOrder.getBigDecimal("sumInsMoney") != null){
                sumInsMoney = sumInsMoney.add(relationOrder.getBigDecimal("sumInsMoney"));
            }
            if (tktPrice != null && relationOrder.getBigDecimal("tktPrice") != null) {
                tktPrice = tktPrice.add(relationOrder.getBigDecimal("tktPrice"));
            }
            if (carrierSumFee != null && relationOrder.getBigDecimal("carrierSumFee") != null) {
                carrierSumFee = carrierSumFee.add(relationOrder.getBigDecimal("carrierSumFee"));
            }
            if ("T".equals(orderType) || "T".equals(statusType)){
                refundOrder = relationOrder;
            }
            if ("G".equals(orderType) || "G".equals(statusType)) {
                if (changeOrder == null){
                    changeOrder = relationOrder;
                }else {
                    Date srcDate = changeOrder.getDate("orderTime");
                    Date targetDate = relationOrder.getDate("orderTime");
                    if (targetDate.after(srcDate)){
                        changeOrder = relationOrder;
                    }
                }
            }
        }
        if (refundOrder != null){
            resultOrder = refundOrder;
        }else if (changeOrder != null){
            resultOrder = changeOrder;
        }
        resultOrder.put("paymentPrice", paymentPrice);
        resultOrder.put("farePrice", farePrice);
        resultOrder.put("constructionPrice", constructionPrice);
        resultOrder.put("oilfee", oilfee);
        resultOrder.put("changeFee", changeFee);
        resultOrder.put("sumInsMoney", sumInsMoney);
        resultOrder.put("tpPrice", tpPrice);
        resultOrder.put("sumCounterFee", sumCounterFee);
        resultOrder.put("sendTicketFee", sendTicketFee);
        resultOrder.put("tktPrice", tktPrice);
        resultOrder.put("carrierSumFee", carrierSumFee);
        return resultOrder;
    }


    /**
     * 处理转换后的结果
     * @param resultJSON
     * @param noteCode
     * @param orderNo
     * @param orderClassification
     * @param resultArray
     */
    private void detailCvtResult(JSONObject resultJSON, String noteCode, String orderNo, String orderClassification, JSONArray resultArray, Map<String,String> notedMap) {

        if (resultJSON != null && resultJSON.getBoolean("success")) {
            JSONArray resultJSONArray = resultJSON.getJSONArray("result");
            if (!CollectionUtils.isEmpty(resultJSONArray)) {
                if (StringUtils.isEmpty(noteCode)) {
                    // 若不传记事类型，则默认转为第一种记事类型
                    JSONObject resJSON = resultJSONArray.getJSONObject(0);
                    String data = resJSON.getString("data");
                    if (!StringUtils.isEmpty(data)) {
                        JSONObject dataJSON = JSON.parseObject(data);
                        getConvertTemplateMapping(dataJSON);
                        /*
                        modify by yangxw1 2021年12月7日 国贸友报账传ncc时，商旅订单单据号进行拼接 start
                         */
//                        dataJSON.put("orderNo", orderNo);
                        List<String> nostr = new ArrayList<String>();
                        notedMap.keySet().forEach(no-> {
                            if(orderNo.startsWith(no.split("_")[0])){
                                nostr.add(no.split("_")[1]);
                            }
                        });
                        dataJSON.put("orderNo",nostr.stream().collect(Collectors.joining(",")));
//                        dataJSON.put("orderClassification", orderClassification);
                        dataJSON.put("orderClassification", orderClassification.equals("flight") ? "1" :orderClassification.equals("train") ?"3":"2" );
                        //end
                        dataJSON.put("billType", resJSON.getString("desbilltypecode"));
                        JSONArray paramArray = new JSONArray();
                        JSONObject paramJson = new JSONObject();
                        paramJson.put("orderNo", orderNo);
                        paramJson.put("orderClassification", orderClassification);
                        paramArray.add(paramJson);
                        List<BriOrderListVO> ordersByOrderNoAndClass = briOrderService.getOrdersByOrderNoAndClass(paramArray);
                        dataJSON.put("brigadeOrders", ordersByOrderNoAndClass);
                        resultArray.add(dataJSON);
                    }
                } else {
                    // 若传记事类型，则按照传入的记事类型生成记事
                    for (Object o : resultJSONArray) {
                        JSONObject resJSON = (JSONObject) o;
                        if (noteCode.equals(resJSON.getString("desbilltypecode"))) {
                            String data = resJSON.getString("data");
                            if (!StringUtils.isEmpty(data)) {
                                JSONObject dataJSON = JSON.parseObject(data);
                                getConvertTemplateMapping(dataJSON);
                                /*
                                modify by yangxw1 2021年12月7日 国贸友报账传ncc时，商旅订单单据号进行拼接 start
                                 */
//                                dataJSON.put("orderNo", orderNo);
                                List<String> nostr = new ArrayList<String>();
                                notedMap.keySet().forEach(no-> {
                                    if(orderNo.startsWith(no.split("_")[0])){
                                        nostr.add(no.split("_")[1]);
                                    }
                                });
                                dataJSON.put("orderNo",nostr.stream().collect(Collectors.joining(",")));
//                                dataJSON.put("orderClassification", orderClassification);
                                dataJSON.put("orderClassification", orderClassification.equals("flight") ? "1" :orderClassification.equals("train") ?"3":"2" );
                                //end
                                dataJSON.put("billType", noteCode);
                                JSONArray paramArray = new JSONArray();
                                JSONObject paramJson = new JSONObject();
                                paramJson.put("orderNo", orderNo);
                                paramJson.put("orderClassification", orderClassification);
                                paramArray.add(paramJson);
                                List<BriOrderListVO> ordersByOrderNoAndClass = briOrderService.getOrdersByOrderNoAndClass(paramArray);
                                dataJSON.put("brigadeOrders", ordersByOrderNoAndClass);
                                resultArray.add(dataJSON);
                            }
                        } else {
                            logger.info("订单类别：" + orderClassification + "，订单号：" + orderNo + "转换结果没有选择的记事类型");
                        }
                    }
                }
            } else {
                logger.info("订单类别：" + orderClassification + "，订单号：" + orderNo + "转换结果为空");
            }
        }
    }

    private void getConvertTemplateMapping(JSONObject dataJSON) {
        Map<String, String> attributeMap = convertTemplateMappingService.queryALLConvertTemplateMapping();
        if (!CollectionUtils.isEmpty(attributeMap)) {
            if (attributeMap.size() > 0) {
                Map<String, Object> changeData = new HashMap<>();
                Iterator<String> it = dataJSON.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next();
                    if (attributeMap.containsKey(key)) {
                        continue;
                    }
                    if (attributeMap.containsValue(key)) {
                        Iterator<Map.Entry<String, String>> attribute = attributeMap.entrySet().iterator();
                        while (attribute.hasNext()) {
                            Map.Entry<String, String> entry = attribute.next();
                            if (entry.getValue().equals(key)) {
                                changeData.put(entry.getKey(), dataJSON.get(key));
                            }
                        }
                    }
                }
                dataJSON.putAll(changeData);
            }
        }
    }

//    /**
//     * 查询此订单关联的退改签订单
//     * @param t
//     * @param <T>
//     * @return
//     */
//    private <T> JSONArray findOrders4TG(T t) {
//        if (t != null) {
//            JSONArray result = new JSONArray();
//            if (t instanceof BriFlightOrder) {
//                BriFlightOrder briFlightOrder = (BriFlightOrder) t;
//                String orderNo = briFlightOrder.getOrderNo();
//                List<BriFlightOrder> briFlightOrdersByParentOrderNo = briFlightOrderService.getBriFlightOrderByParentOrderNo(orderNo);
//                if (!CollectionUtils.isEmpty(briFlightOrdersByParentOrderNo)) {
//                    for (BriFlightOrder flightOrder : briFlightOrdersByParentOrderNo) {
//                        CnvFlightOrderDO briFlightOrderByOrderNo = briFlightOrderService.getBriFlightOrderByOrderNo(flightOrder.getOrderNo());
//
//                    }
//                }
//                String parentOrderNo = briFlightOrder.getParentOrderNo();
//                if (StringUtils.isEmpty(parentOrderNo)) {
//                    CnvFlightOrderDO briFlightOrderByOrderNo = briFlightOrderService.getBriFlightOrderByOrderNo(parentOrderNo);
//                }
//            } else if (t instanceof BriTrainOrder) {
//                BriTrainOrder briTrainOrder = (BriTrainOrder) t;
//            } else if (t instanceof BriHotelOrder) {
//                BriHotelOrder briHotelOrder = (BriHotelOrder) t;
//            } else if (t instanceof BriCarOrder) {
//                BriCarOrder briCarOrder = (BriCarOrder) t;
//            }
//            return result;
//        }
//        return null;
//    }

    /**
     * 返回结果中添加申请单号及航程信息
     * @param jsonObject
     */
    private void addApplyIdAndflightInfos(JSONObject jsonObject) {
        if (jsonObject != null && jsonObject.getBoolean("success") && jsonObject.get("data") instanceof JSONArray && !CollectionUtils.isEmpty(jsonObject.getJSONArray("data"))) {
            for (Object data : jsonObject.getJSONArray("data")) {
                JSONObject noteData = (JSONObject) data;
                String pk = noteData.getString("pk");
                List<String> notePks = new CopyOnWriteArrayList<>();
                notePks.add(pk);
                List<BriOrderNote> orderNotesByNotePks = briOrderNoteMapper.getOrderNotesByNotePks(notePks);
                if (!CollectionUtils.isEmpty(orderNotesByNotePks)) {
                    String orderId = orderNotesByNotePks.get(0).getOrderId();
                    String orderType = orderNotesByNotePks.get(0).getOrderType();
                    JSONArray flightInfosJson = new JSONArray();
                    if (BriOrderNote.FLIGHT_ORDER.equals(orderType)) {
                        BriFlightOrder flightOrder = briFlightOrderService.selectById(orderId);
                        // 返回信息中增加申请单号
                        noteData.put("applyId", flightOrder.getRelateYbzId());
                        // 返回信息中增加航程信息
                        if (flightOrder != null) {
                            List<BriFlightInfo> briFlightInfos = briFlightInfoService.getBriFlightInfo(flightOrder.getOrderNo());
                            if (!CollectionUtils.isEmpty(briFlightInfos)) {
                                for (BriFlightInfo briFlightInfo : briFlightInfos) {
                                    JSONObject flightInfoJson = new JSONObject();
                                    flightInfoJson.put("flightNo", briFlightInfo.getFlightNo());
                                    flightInfoJson.put("yprice", briFlightInfo.getYprice());
                                    flightInfoJson.put("lowestPrice", briFlightInfo.getLowestPrice());
                                    flightInfoJson.put("classRebate", briFlightInfo.getClassRebate());
                                    flightInfoJson.put("classLevelName", briFlightInfo.getClassLevelName());
                                    flightInfoJson.put("classLevelCode", briFlightInfo.getClassLevelCode());
                                    flightInfoJson.put("classCode", briFlightInfo.getClassCode());
                                    flightInfoJson.put("tgq", briFlightInfo.getTgq());
                                    flightInfosJson.add(flightInfoJson);
                                }
                            }
                        }
                    }
                    noteData.put("flightInfo", flightInfosJson);
                }
            }
        }
    }
}
